package com.cqut.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;








import com.cqut.dao.LoginMapper;
import com.cqut.dto.LoginDTO;
import com.cqut.dto.LoginInfoDTO;
import com.cqut.model.ProblemManager;
import com.cqut.model.User;
import com.cqut.service.ILoginService;
import com.cqut.util.StringUtil;
import com.cqut.util.SystemConstants;
import com.cqut.util.jwt.JwtUtil;
import com.scienjus.authorization.manager.TokenManager;

/**
 * @author zzk
 * */
@Service
public class LoginService implements ILoginService{
	// 发行人
	private String issuer;
	
	// 面向用户
	private String subject;
	
	// api密匙
	private String apiKeySecret;
	
	private TokenManager tokenManager;

	@Resource(name="loginMapper")
	private LoginMapper loginMapper;
	
	public static final String TOKEN_KEY = "token";
	public static final String ROLE_TYPE_KEY = "roleType";
	public static final String ORG_ID_KEY = "orgId";
	public static final String USER_NO_KEY = "userNo";
	private static final String ROLE_NAME = "roleName";
	private static final String USER_ID = "userId";
	
	public void setIssuer(String issuer) {
		this.issuer = issuer;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public void setApiKeySecret(String apiKeySecret) {
		this.apiKeySecret = apiKeySecret;
	}
	
	public void setTokenManager(TokenManager tokenManager) {
		this.tokenManager = tokenManager;
	}
	
	
	/**
	 * 学生登录
	 */
	@Override
	public Map<String, Object> loginForStudent(LoginDTO loginDTO) {
		// TODO Auto-generated method stub
		Map<String, Object> rs = login(loginDTO, SystemConstants.ST_ROLE_ID,"0");
		//rs.put(ROLE_NAME, SystemConstants.ST_ROLE_TYPE);
		return rs;
	}
	
	/**
	 * 系统操作员登录
	 */
	@Override
	public Map<String, Object> loginForOP(LoginDTO loginDTO) {
		// TODO Auto-generated method stub
		Map<String, Object> rs = login(loginDTO, SystemConstants.OP_ROLE_ID,"1");
		//rs.put(ROLE_NAME, SystemConstants.OP_ROLE_TYPE);
		return rs;
	}
	
	/**
	 * 评委登录
	 */
	@Override
	public Map<String, Object> loginForJD(LoginDTO loginDTO) {
		// TODO Auto-generated method stub
		Map<String, Object> rs = loginJD(loginDTO, SystemConstants.JD_ROLE_ID,"2");
		//rs.put(ROLE_NAME, SystemConstants.JD_ROLE_TYPE);
		return rs;
	}
	
	private Map<String, Object> loginJD(LoginDTO loginDTO, String roleId,String roleType) {
		List<Map<String, Object>> users = loginMapper.loginjd(loginDTO, roleId, roleType);

		if(users.size() <= 0)
			return null;
		
		Map<String, Object> rs = new HashMap<String, Object>();
		
		String userId = users.get(0).get("userId").toString();
		String token = createToken(userId);
		
		tokenManager.createRelationship(userId, token);

		rs.put(TOKEN_KEY, token);
		rs.put(ROLE_TYPE_KEY, SystemConstants.getRoleType(roleId));
		rs.put(USER_ID,users.get(0).get("userId"));
		rs.put(USER_NO_KEY,  users.get(0).get("userNo"));
		return rs;
	}
	
	/**
	 * 竞赛管理员登录
	 */
	@Override
	public Map<String, Object> loginForCP(LoginDTO loginDTO) {
		// TODO Auto-generated method stub
		Map<String, Object> rs = login(loginDTO, SystemConstants.JD_ROLE_ID,"3");
		//rs.put(ROLE_NAME, SystemConstants.JD_ROLE_TYPE);
		return rs;
	}
	
	/**
	 * 登录的通用方法
	 * 实现逻辑：查询一个存在该角色的user
	 * */
	private Map<String, Object> login(LoginDTO loginDTO, String roleId,String roleType) {
		List<Map<String, Object>> users = loginMapper.login(loginDTO, roleId, roleType);

		if(users.size() <= 0)
			return null;
		
		Map<String, Object> rs = new HashMap<String, Object>();
		
		String userId = users.get(0).get("userId").toString();
		String token = createToken(userId);
		
		tokenManager.createRelationship(userId, token);

		rs.put(TOKEN_KEY, token);
		rs.put(ROLE_TYPE_KEY, SystemConstants.getRoleType(roleId));
		rs.put(USER_ID,users.get(0).get("userId"));
		rs.put(USER_NO_KEY,  users.get(0).get("userNo"));
		return rs;
	}
	
	private String createToken(String userid) {
		return JwtUtil.createJWT(userid, issuer, subject, apiKeySecret);
	}

	@Override
	public boolean logout(String token) {
		// 如果系统中不存在这个token
		if(StringUtil.isNullOrEmpty(tokenManager.getKey(token)))
			return false;
		
		tokenManager.delRelationshipByToken(token);
		
		return true;
	}
	
	/**
	 * 根据用户ID查找到对应的模块
	 */
	@Override
	public List<Map<String, Object>> findModuelsByOrg(String userId,LoginInfoDTO userInfo,int type) {
		/*if(!userInfo.getCurUserid().endsWith(SystemConstants.ADMIN_UID)){
			userId=" ";
		}*/
		System.out.println(userId);
		List<Map<String, Object>> result=loginMapper.findModuelsByOrg(userId);
		
		if(result.size()==0 || type!=0){
			return result;
		}
		return convert(result);
	}
	
	/**
	 * 将查询得到的数据转换成一定的格式
	 * */
	private List<Map<String, Object>> convert(List<Map<String, Object>> list) {
		List<Map<String, Object>> test = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		
		if (list != null) {
			int initialLength = ((String) list.get(0).get("menu_id")).length();
			int i = 0;
			for (i = 0; i < list.size(); i++) {
				String parent = (String) list.get(i).get("menu_id");
				Map<String, Object> map = new HashMap<String, Object>();
				List<Map<String, Object>> children = new ArrayList<Map<String, Object>>();

				if (parent.length() == initialLength) {
					map = list.get(i);
					for (int j = i + 1; j < list.size(); j++) {
						if (((String) list.get(j).get("menu_id")).length() == initialLength) {
							i = j - 1;
							break;
						}
						children.add(list.get(j));
					}

					map.put("children", children);
					test.add(map);
					
					result.add(map);
				}

			}
		}
		
		for(int j=0;j<test.size()-1;j++){
			for(int l=0;l<test.size()-1-j;l++){
				Map<String, Object> map = test.get(l);
				int line=Integer.parseInt(map.get("order_no").toString());
				
				Map<String, Object> secondMap = test.get(l+1);
				int secondLine=Integer.parseInt(secondMap.get("order_no").toString());
					
				if (line > secondLine){
					test.set(l+1, map);
					test.set(l, secondMap);
                 }
			}
		}
		
		for (int j = 0; j < test.size(); j++) {
			Map<String, Object> map = test.get(j);
			int line=Integer.parseInt(map.get("order_no").toString());
			
			List<Map<String, Object>> temp=new ArrayList<Map<String, Object>>();
			temp=(List<Map<String, Object>>) map.get("children");
			
			//冒泡排序
			for (int i = 0; i < temp.size()-1; i++)
            {
                for (int k = 0; k < temp.size()- i - 1; k++)
                {
                	Map<String, Object> map1=temp.get(k);
    				int line1=Integer.parseInt(map1.get("order_no").toString());
                	
                	Map<String, Object> map2=temp.get(k+1);
                	int line2=Integer.parseInt(map2.get("order_no").toString());
                	
                    if (line1 > line2){ 
                       temp.set(k+1, map1);
                       temp.set(k, map2);
                    }
                }
            }
			
			
		}
		
		
		return test;
	}
	
}

















